<template>
  <div>
    <a-row class="operate-row mb-15">
      <a-col :span="isView ? 24 : 12 " :class="{'mb-15': true}">
        <div class='blue-line line-height-32'>{{$t('hangManage.processInfo')}}</div>
      </a-col>
      <a-col :span="12" :class="{'text-right': !isView}">
        <span class="text-red">*</span>{{ $t('other.versionName') }}：
        <a-input style="width: 180px" disabled v-model:value="versionName" />
      </a-col>
      <a-col :span="12" class="text-right" v-if="isView" >
        <a-space>
          <a-button type="warning" @click="onDelete" :disabled="disabledBtn">{{$t('common.delMore')}}</a-button>
          <a-button type="primary" :disabled="disabled" @click="addProc('one')">{{ $t('other.addProcess') }}</a-button>
          <a-button type="primary" :disabled="disabled" @click="addProc('more')">{{ $t('other.addFromProcess') }}</a-button>
        </a-space>
      </a-col>

    </a-row>
    <div class="process--schedule-list-container">
      <header>
        <div>
          <a-checkbox :indeterminate="indeterminate" v-model:checked="checkedAll" :disabled="!isView" @change="onCheckedAll"></a-checkbox>
        </div>
        <div v-for="(item, index) in listHeaders" :key="index" :class="[{'fixed-width': [ 1, 2, 5, 7].includes(index)},{'fixed-width1': index== 4} ]">
          <span class="text-red" v-if="[0,1,2,3,4,5,9].includes(index)">*</span>{{item}}
        </div>
        <div class="fixed-width1" v-if="isView">{{$t('common.operate')}}</div>
      </header>
      <a-spin :spinning="loading">
        <a-form ref="listFormRef" :model="dataSource">
          <draggable :list="dataSource" is='draggable' filter=".unmover" :disabled="disabled || !isView" handle=".can-sort-schedule" animation="300"
                     :scroll="true" force-fallback="true" item-key="index" @sort="handleSort" @start="handleStart">
            <template #item="{element, index}">
              <div :class="{'can-sort-schedule': index != 0}">
                <div class="drag-process-list-container mt-12">
                  <div class="unmover">
                    <a-checkbox :disabled="(!index && isView) || !isView" v-model:checked="element.checked" @change="onCheckedOne"></a-checkbox>
                  </div>
                  <div>
                    <a-form-item v-if="element.edit" :name="[index, 'section']" :rules="processRule.section">
                      <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="element.section" min="0" allowClear>
                        <a-select-option v-for="item in sectionList" :key="item" :value="item.name">{{ item.name }}</a-select-option>
                      </a-select>
                    </a-form-item>
                    <span v-else>{{element.section}}</span>
                  </div>
                  <div class="fixed-width">
                    <a-form-item v-if="element.edit" :name="[index, 'sortField']" :rules="processRule.sortField">
                      <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="element.sortField" :min="1" />
                    </a-form-item>
                    <span v-else>{{element.sortField}}</span>
                  </div>
                  <div class="fixed-width">
                    <a-form-item v-if="element.edit" :name="[index, 'processNo']" :rules="processRule.processNo">
                      <a-input-number :placeholder="$t('common.pleaseInput')" :min="0" v-model:value="element.processNo" />
                    </a-form-item>
                    <span v-else>{{element.processNo}}</span>
                  </div>
                  <div>
                    <a-form-item v-if="element.edit" :name="[index, 'name']" :rules="processRule.name">
                      <a-input :placeholder="$t('common.pleaseInput')" v-model:value.trim="element.name" :maxLength="29" />
                    </a-form-item>
                    <a-tooltip v-else>
                      <template #title>{{element.name}}</template>
                      <span>{{element.name}}</span>
                    </a-tooltip>
                  </div>
                  <div class="fixed-width">
                    <a-form-item v-if="element.edit" :name="[index, 'processCode']" :rules="processRule.processCode">
                      <a-input :placeholder="$t('common.pleaseInput')"  v-model:value="element.processCode" />
                    </a-form-item>
                    <span v-else>{{element.processCode}}</span>
                  </div>
                  <div class="fixed-width1">
                    <a-form-item v-if="element.edit" :name="[index, 'standardSeconds']" :rules="processRule.standardSeconds">
                      <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="element.standardSeconds" min="" />
                    </a-form-item>
                    <span v-else>{{element.standardSeconds}}</span>
                  </div>
                  <div class="fixed-width">
                    <a-form-item v-if="element.edit" :name="[index, 'labourCost']" :rules="processRule.labourCost">
                      <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="element.labourCost" min="0" />
                    </a-form-item>
                    <span v-else>{{element.labourCost}}</span>
                  </div>
                  <div>
                    <a-form-item v-if="element.edit" :name="[index, 'processGuide']">
                      <a-input :placeholder="$t('common.pleaseInput')" v-model:value.trim="element.processGuide" :maxLength="99" />
                    </a-form-item>
                    <a-tooltip v-else>
                      <template #title>{{element.processGuide}}</template>
                      <span>{{element.processGuide}}</span>
                    </a-tooltip>

                  </div>
                  <div class="fixed-width unmover">
                    <span class="code-link" v-if="element.edit" @click="operateImg(element,index, true)">{{$t('common.edit')}}</span>
                    <span class="code-link" v-else @click="operateImg(element,index)">
                      <span v-if="element.processPictureUrlList && element.processPictureUrlList.length">{{$t('common.look')}}</span>
                    </span>
                  </div>

                  <div>
                    <a-form-item v-if="element.edit" :name="[index, 'professionId']" :rules="processRule.professionId">
                      <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="element.professionId" min="0" allowClear>
                        <a-select-option v-for="item in professionIdList" :key="item" :value="item.id">{{ item.name }}</a-select-option>
                      </a-select>
                    </a-form-item>
                    <span v-else> {{getFieldText(professionIdList,element.professionId,'id','name')}} </span>
                  </div>
                  <div>
                    <a-form-item v-if="element.edit" :name="[index, 'skillGradeId']">
                      <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="element.skillGradeId" min="0" allowClear>
                        <a-select-option v-for="item in skillGradeId" :key="item" :value="item.id">{{ item.grade }}</a-select-option>
                      </a-select>
                    </a-form-item>
                    <span v-else>{{getFieldText(skillGradeId,element.skillGradeId,'id','grade')}} </span>
                  </div>


                  <div class="fixed-width1 unmover" v-if="isView">
                    <span v-if="element.edit">
                      <span class="code-link" @click="onSave(element, index)">{{$t('common.save')}}</span>
                      <a-divider type="vertical" />
                      <span class="code-link" @click="onCancel(element, index)">{{$t('common.cancel')}}</span>
                    </span>
                    <span v-else class="code-link" @click="onEditPro(element)">{{ $t('common.editor') }}</span>
                  </div>
                </div>
              </div>

            </template>
          </draggable>
        </a-form>
      </a-spin>
      <CustomModal ref="customModalRef" @ok="onDeleteOk" />
      <ProcessModal ref="processModalRef" @ok="onAdd" />
      <UploadModal ref="uploadModalRef" @ok="onImgOk" />
    </div>
  </div>
</template>
<script setup>
import ProcessModal from '@/views/makeManage/makeProcess/newModules/processModal.vue'
import UploadModal from '@/views/makeManage/makeProcess/newModules/uploadModal.vue'
import CustomModal from '@/components/confirmModal/customModal.vue'
import draggable from 'vuedraggable'
import { listHeaders, processRule } from './config'
import { computed, ref, onMounted ,watch} from 'vue'
import {  getFieldText } from '@/utils'
import { cloneDeep } from 'lodash'
import { useRoute } from 'vue-router'
import axios from "@/utils/request"
import { message } from 'ant-design-vue'
import { store } from "@/store"
import i18n from '@/locales/index' 
const { t } = i18n.global
let loading = ref(false)
let disabled = computed(() => dataSource.value.some(i => i.edit))
let disabledBtn = computed(() => dataSource.value.every(i => !i.checked))
let sectionList = computed(() => { return store.state.normalData.sectionList }) // t('basicData.section')列表
let route = useRoute()
let isAdd = ref(false)
let isEdit = ref(false)
let isView = ref(false)
let listFormRef = ref()
let customModalRef = ref()
let processModalRef = ref()
let uploadModalRef = ref()

let indeterminate = ref(false)
let checkedAll = ref(false)
let originList = ref([])
let originSortList = ref([])
let maxNum = ref(0)
let dataSource = ref([])
let dataList = ref({})
let versionName = ref('')
let urlType = ref('')

let professionIdList = ref([])
let skillGradeId = ref([])

const props = defineProps({
  urlType: { type: String, default: () => 'ie' },
  dataList: { type: Object, default: () => {} },
  isView: { type: Boolean, default: () => false }
})

watch(
    () => props.isView,
    (newVal) => {
      isView.value = cloneDeep(newVal)
    },
    { deep: true, immediate: true }
)
watch(
    () => props.urlType,
    (newVal) => {
      urlType.value = cloneDeep(newVal)
    },
    { deep: true, immediate: true }
)

const onDelete = async () => {
  let notOrigin = dataSource.value.filter(i => i.checked).every(i => !i.isOrigin)
  // console.log("🚀 ~  ~ notOrigin^^^^^^^^^^", notOrigin)
  if (notOrigin) {
    initDelData()
    return
  }
  /*try {
    const res = await axios.getAction('/api/mo/mo-proc/get', { id: route.query.processId })
    let { status, isScheduleBill } = res.data
    console.log('******', status, isScheduleBill);
    if (status == 0 && isScheduleBill == 0) {
      deleteInfo()
      return
    }
    let opts = {
      content: isScheduleBill == 0 ? '{{ $t('common.del') }}后，关联工艺{{$t('hangManage.road')}}对应工序和工序下的站点也将{{ $t('common.del') }}' : '当前t('basicData.processVer')关联的工艺{{$t('hangManage.road')}}正被排产单使用中，请先解除其绑定关系再{{ $t('common.del') }}。',
      needOperate: isScheduleBill == 0,
      btnText: isScheduleBill == 0 ? '{{ $t('common.del') }}' : '{{$t('common.ok')}}'
    }
    customModalRef.value.open(opts)
  } catch {
    console.log('err');
  }*/
}
const onDeleteOk = (value) => {
  if (value) deleteInfo()
}
const deleteInfo = async () => {
  let params = dataSource.value.filter(i => i.checked).map(i => i.id)
  const res = await axios.postAction('/api/mo/mo-proc/delete-detail', params)
  if (res.success) initDelData()
}
const initDelData = (updateTable = true) => {
  checkedAll.value = false
  indeterminate.value = false
  updateTable && (dataSource.value = dataSource.value.filter(i => !i.checked))
  initSortInfo()
}
const addProc = (type) => {
  initSortInfo()
  if (type == 'one') {
    const newProcess = { section: "{{$t('components.dg')}}", moId: route.query.id, standardSeconds: 30, labourCost: 1, statue: true, isAdd: true, edit: true }
    dataSource.value.push(newProcess)
  } else {
    // console.log('____++++++++++++maxNum', maxNum.value);
    let selectedIds = dataSource.value.filter(i => i.originId).map(i => i.originId)
    processModalRef.value.open(props.styleId, selectedIds)
  }
}
const onAdd = (value) => {
  value.forEach(i => {
    i.sortField = ++maxNum.value
    i.originId = i.id
    delete i.id
    dataSource.value.push({ ...i })
  })
  initSortInfo()
}
const operateImg = (record, index, isEdit) => {
  uploadModalRef.value.open(record.processPictureUrlList, index, isEdit)
}
const onImgOk = (fileList, index) => {
  dataSource.value[index].processPictureUrlList = fileList
}
const onEditPro = (record) => {
  if (disabled.value) {
    message.warning(t('other.operateOne'))
    return
  }
  record.edit = true
  handleStart()
}
const onCancel = (record, index) => {
  if (record.isAdd) {
    dataSource.value.splice(index, 1)
    initSortInfo()
    record.edit = false
  } else {
    originList.value[index].edit = false
    dataSource.value = originList.value
  }
  initDelData(false)
}
const onSave = async (record, index) => {
  await listFormRef.value.validateFields()
  let list = cloneDeep(dataSource.value)
  list.splice(index, 1)
  let uniqueValue = list.some(i => (i.sortField == record.sortField) || (i.processNo == record.processNo) || (i.name == record.name))
  if (uniqueValue) {
    message.warning(t('other.ruleSchProcessNameOnly'))
    return
  }
  record.edit = false
  record.isAdd = false
  initSortInfo()
  return true
}
const onCheckedAll = () => {
  dataSource.value.forEach((i, index) => {
    if (!isView.value) {
      i.checked = checkedAll.value
    } else {
      index && (i.checked = checkedAll.value)
    }
  })
  indeterminate.value = false
}
const onCheckedOne = () => {
  let list = isView.value ? dataSource.value : cloneDeep(dataSource.value)
  !isView.value && list.shift()
  checkedAll.value = list.every(i => i.checked)
  if (checkedAll.value) {
    indeterminate.value = false
  } else {
    indeterminate.value = list.some(i => i.checked)
  }
}
const handleStart = () => {
  originList.value = cloneDeep(dataSource.value)
}
const handleSort = (e) => {
  if (e.newIndex == 0) {
    message.warning(t('other.firstCanNotSort'))
    dataSource.value = originList.value
  } else {
    dataSource.value.forEach((el, index) => {
      el.sortField = originSortList.value[index]
    })
  }
}
const initSortInfo = () => {
  originSortList.value = dataSource.value.map(i => i.sortField)
  maxNum.value = Math.max(...originSortList.value) < 0 ? 0: Math.max(...originSortList.value)
  // console.log("************************************ ",originSortList.value, maxNum.value)
}

// watch(() => props.tableData, (newVal) => {
//   console.log('+^^^^^^^^^^^^newVal^^^', newVal)
//   if (newVal) {
//     dataSource.value = cloneDeep(newVal)
//     dataSource.value.forEach(i => {
//       i.isOrigin = true
//       i.isAdd = false
//       i.originId = i.id
//     })
//     initSortInfo()
//   }
// }, { deep: true, immediate: true })

watch(
    () => props.dataList,
    (newVal) => {
      dataList.value = cloneDeep(newVal)
      // let processFirstObj = {section: "{{$t('components.dg')}}", moId: "", standardSeconds: 30, labourCost: 1, sortField: 1, processNo: 1, name: "挂片", processCode: 1, professionId: "", skillGradeId: ""}
      if (urlType.value == 'loc'){
        if(dataList.value['autoRoadmapProcVO']){
          dataSource.value =dataList.value['autoRoadmapProcVO']['detailList'] && dataList.value['autoRoadmapProcVO']['detailList'].length>0 ?dataList.value['autoRoadmapProcVO']['detailList']: [{section: "{{$t('components.dg')}}", moId: "", standardSeconds: 30, labourCost: 1, sortField: 1, processNo: 1, name: "挂片", processCode: 1, professionId: "", skillGradeId: ""}]
          versionName.value = dataList.value.autoRoadmapProcVO.name ?? ''
        }
      }else{
        if(dataList.value['ieRoadmapProcVO']){
          dataSource.value =dataList.value['ieRoadmapProcVO']['detailList'] && dataList.value['ieRoadmapProcVO']['detailList'].length>0 ?dataList.value['ieRoadmapProcVO']['detailList']: [{section: t('components.dg'), moId: "", standardSeconds: 30, labourCost: 1, sortField: 1, processNo: 1, name: t('hangManage.hang'), processCode: 1, professionId: "", skillGradeId: ""}]
          versionName.value = dataList.value.ieRoadmapProcVO.name ?? ''
        }
      }
      initSortInfo()
      // console.log(dataList.value,'dataList------------------************')
    },
    { deep: true, immediate: true }
)

onMounted(async () => {
  await store.dispatch("getSection")
  originSortList.value = []
  // isView.value = true
  isAdd.value = route.path == '/makeManage/scheduleProcess/add'
  isEdit.value = route.path == '/makeManage/scheduleProcess/edit'
  // isView.value = route.path === 'makeManage/scheduleProcess/details'
  if (route.path === 'makeManage/scheduleProcess/details'){
    isView.value = true
  }
  const res = await axios.postAction('/api/basic/profession/list-profession')
  if (res.success){
    professionIdList.value = res.data;
  }
  const resSkill = await axios.postAction('/api/basic/skill-grade/list')
  if (resSkill.success){
    skillGradeId.value = resSkill.data;
  }


})
defineExpose({
  dataSource,
  dataList,
  onSave
})
</script>
